# ============== 导入通用的基础模块 ==============
from resources_base.module_base.import_base import *
from resources_base.module_base import utils
from resources_base.module_base import sqlhelper

# ============== 导入数据模块 ==============
from studentweb.models import Student

# ============== 导入腾讯云cos ==============
from resources_base.module_base.tencent import cos



@csrf_exempt
def list_values(request):
    """获取所有学生信息"""
    try:
        # 获取传递的数据
        rec = json.loads(request.body.decode("utf-8"))
        # 获取分页中当前的页码
        page = int(rec['page'])
        # 获取分页中每页的记录条数
        limit = int(rec['limit'])
        # 获取的查询字符串  -[学号，姓名，手机号码，邮箱，家庭住址 ]
        q_str = rec.get('q_str')
        # 获取的部门信息
        q_dept = rec.get('q_dept')
        # 获取的职位信息
        q_position = rec.get('q_position')


        # 获取所有的学生信息
        objs_student = list(Student.objects.filter(dept__icontains=q_dept, position__icontains=q_position)
                            .filter(Q(sno__icontains=q_str) |
                                    Q(name__icontains=q_str) |
                                    Q(mobile__icontains=q_str)|
                                    Q(email__icontains=q_str)|
                                    Q(address__icontains=q_str)).values())
        # ==== 获取所有的职位信息填充下拉框 ====
        position_select_data = []
        # 便利所有的数据
        for item in objs_student:
            # 拼接临时的dict
            temp_dict = {'value': item.get('position'), 'label': item.get('position')}
            # 判断是否存在，不存在附加到position_select_data
            if temp_dict not in position_select_data:
                position_select_data.append(temp_dict)
        # 获取当前页的学生信息
        one_page_student = objs_student[(page - 1) * limit: page * limit]
        # 返回
        return JsonResponse({'status': True, 'data': one_page_student, 'count':len(objs_student), 'positions': position_select_data})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '获取数据出现异常！具体原因：' + str(e)})


@csrf_exempt
def add_value(request):
    """添加学生信息"""
    try:
        # 接受传递的数据
        rec = json.loads(request.body.decode("utf-8"))
        # 判断学号是否存在
        is_sno_exists = Student.objects.filter(sno=rec.get('sno')).exists()
        # 如果存在，返回
        if is_sno_exists:
            return JsonResponse({'status': False, 'error': '学号已存在！' })

        # 添加
        Student.objects.create(sno=rec.get('sno'), name=rec.get('name'),gender=rec.get('gender'),
                               dept=rec.get('dept'), position=rec.get('position'),
                               birthday=rec.get('birthday'), mobile=rec.get('mobile'),
                               email=rec.get('email'), address=rec.get('address'), image=rec.get('image'))
        # 返回成功
        return JsonResponse({'status': True})
    except Exception as e:
        # 返回
        return JsonResponse({'status': False, 'error': '添加学生出现未知的异常，具体原因：' + str(e)})


@csrf_exempt
def edit_value(request):
    """编辑学生信息"""
    try:
        # 接受传递的数据
        rec = json.loads(request.body.decode("utf-8"))

        # 获取当前对象
        obj_student = Student.objects.filter(sno=rec.get('sno')).first()
        # 修改
        obj_student.name = rec.get('name')
        obj_student.gender = rec.get('gender')
        obj_student.dept = rec.get('dept')
        obj_student.position = rec.get('position')
        obj_student.birthday = rec.get('birthday')
        obj_student.mobile = rec.get('mobile')
        obj_student.email = rec.get('email')
        obj_student.address = rec.get('address')
        obj_student.image = rec.get('image')
        # 保存
        obj_student.save()
        # 返回成功
        return JsonResponse({'status': True})
    except Exception as e:
        # 返回
        return JsonResponse({'status': False, 'error': '编辑学生出现未知的异常，具体原因：' + str(e)})


@csrf_exempt
def del_value(request):
    """删除学生信息"""
    try:
        # 接受传递的数据
        rec = json.loads(request.body.decode("utf-8"))
        # 获取学生照片的本地路径
        image_path = os.path.join(settings.MEDIA_ROOT,rec.get('image').split('/')[-1])
        # 删除文件
        if os.path.exists(image_path):
            # 删除
            os.remove(image_path)
        # 删除数据记录
        Student.objects.filter(sno=rec.get('sno')).delete()
        # 返回成功
        return JsonResponse({'status': True})
    except Exception as e:
        # 返回
        return JsonResponse({'status': False, 'error': '删除学生出现未知的异常，具体原因：' + str(e)})

"""
@csrf_exempt
def upload(request):
    # 调用后台的文件上传
    response = utils.upload_file(request, type=1)
    # 返回
    return JsonResponse(response)
"""


@csrf_exempt
def upload(request):
    """
    上传到腾讯云的对象存储
    """
    # 接收前台传递的文件 --- 前台提交上传的文件 key必须要是‘file’ --- 对象
    rev_file = request.FILES.get('file')
    # 判断是否有文件
    if not rev_file:
        # 返回
        return {'status': False, 'error': "上传的文件不存在！"}
    # 获取信息的名称
    new_name = utils.get_random_str_uuid() + os.path.splitext(rev_file.name)[1]
    # 上传
    res = cos.upload_file(settings.COS_SECRET_ID, settings.COS_SECRET_KEY, 'ap-nanjing', 'traingmgr-student-1301712701',
                          rev_file, new_name)
    print(res)
    # 返回
    return JsonResponse(res)



@csrf_exempt
def upload_excel(request):
    """上传Excel文件"""
    # ==== step01: Excel文件上传 ====
    res_upload = utils.upload_file(request, type=2)
    # 判断是否上传完成
    if not res_upload.get('status'):
        # 报错
        return JsonResponse({'status': False, 'error': res_upload.get('error')})

    # ==== step02: Excel文件数据读取====
    # 获取Excel路径
    excel_path = os.path.join(settings.BASE_DIR, 'apps', 'media', res_upload.get('name'))
    # 开始读取
    res_read_excel = utils.read_excel_list(excel_path, 'Sheet1', title=True)
    # 判断是否读取成功
    if not res_read_excel.get('status'):
        # 报错
        return JsonResponse({'status': False, 'error': res_read_excel.get('error')})

    # ==== step03: 批量写入到数据库====
    sql = """
    Insert Into Student(sno, name, gender, dept, position, birthday, mobile, email, address) 
    values (%s,%s,%s,%s,%s,%s,%s,%s,%s)
    """
    # 批量上传
    res_bulk_insert = sqlhelper.bulk_insert(sql, res_read_excel.get('data'))
    # 判断是否成功
    if not res_bulk_insert.get('status'):
        return JsonResponse({'status': False, 'error': res_bulk_insert.get('error')})
    else:
        return JsonResponse({'status': True})


@csrf_exempt
def export_excel(request):
    """导出到Excel"""
    # 获取传递的数据
    rec = json.loads(request.body.decode("utf-8"))
    # 获取的查询字符串  -[学号，姓名，手机号码，邮箱，家庭住址 ]
    q_str = rec.get('q_str')
    # 获取的部门信息
    q_dept = rec.get('q_dept')
    # 获取的职位信息
    q_position = rec.get('q_position')

    # 获取所有的学生信息
    objs_student = list(Student.objects.filter(dept__icontains=q_dept, position__icontains=q_position)
                        .filter(Q(sno__icontains=q_str) |
                                Q(name__icontains=q_str) |
                                Q(mobile__icontains=q_str) |
                                Q(email__icontains=q_str) |
                                Q(address__icontains=q_str)).values())

    # 获取path
    new_name = utils.get_random_str_uuid() + ".xlsx"
    path = os.path.join(settings.MEDIA_ROOT,  new_name)
    keys = ['sno','name','gender','birthday','dept','position', 'mobile','email','address']
    title = ['学号','姓名','性别','出生日期','部门','职位','手机号码','邮箱地址','住址']
    # 调用
    response = utils.export_to_excel(objs_student, path, 'student', keys, title)
    # 返回
    if response.get('status'):
        return JsonResponse({'status': True, 'data': "http://192.168.182.140:8000/media/" + new_name})
    else:
        return JsonResponse({'status': False, 'error': response.get('error')})
